/**
 * 
 */
package com.worksmap.core.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taobao.api.internal.util.WebUtils;
import com.worksmap.core.constant.RateConstant;
import com.worksmap.core.dao.UserDao;
import com.worksmap.core.entity.TaoBaoSeller;
import com.worksmap.core.entity.User;
import com.worksmap.core.exception.WebUtilException;
import com.worksmap.core.service.CookieService;
import com.worksmap.core.service.LoginService;
import com.worksmap.core.service.SellerConfigService;
import com.worksmap.core.service.UserService;
import com.worksmap.core.util.CookieUtil;
import com.worksmap.core.util.DaoException;
import com.worksmap.core.util.StringUtil;

/**
 * @author jack
 *
 */
@Service
public class UserServiceImpl implements UserService {
	
	Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	UserDao userDao;
	@Autowired
	CookieService cookieService;
	@Autowired
	LoginService loginService;
	@Autowired
	SellerConfigService sellerConfigService;
	
	@Override
	public TaoBaoSeller getSellerInfo(String code, String state, HttpServletResponse response) throws WebUtilException{
		TaoBaoSeller seller = new TaoBaoSeller();
//		List<NameValuePair> params = new ArrayList<NameValuePair>();
//		params.add(new BasicNameValuePair("client_id", RateConstant.appkey));
//		params.add(new BasicNameValuePair("client_secret", RateConstant.appSecret));
//		params.add(new BasicNameValuePair("grant_type", "authorization_code"));
//		params.add(new BasicNameValuePair("code", code)); //授权码
//		params.add(new BasicNameValuePair("redirect_uri", RateConstant.redirectUri));
//		params.add(new BasicNameValuePair("state", state));
//		params.add(new BasicNameValuePair("view", "web"));
//		String body = WebUtil.postMethod(RateConstant.tokenUrl, params);
		Map<String, String> param = new HashMap<String, String>();
		param.put("client_id", RateConstant.appkey);
		param.put("client_secret", RateConstant.appSecret);
		param.put("grant_type", "authorization_code");
		param.put("code", code);
		param.put("redirect_uri", RateConstant.redirectUri);
		param.put("state", state);
		param.put("view", "web");
		String body = "";
		try {
			body = WebUtils.doPost(RateConstant.tokenUrl, param, 3000, 3000);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	    JSONObject jsonSeller = JSONObject.fromObject(body);  //body是json串
	    if(jsonSeller.containsKey("error")){
	    	logger.error("用户授权失败：" + jsonSeller.getString("error") + jsonSeller.getString("error_description"));
	    	throw new WebUtilException(jsonSeller.getString("error"), new Throwable(jsonSeller.getString("error_description")));
	    }
	    seller = (TaoBaoSeller)JSONObject.toBean(jsonSeller, TaoBaoSeller.class);
	    if(seller != null){
	    	maintainUser(seller);
	    }
	    try {
	    	cookieService.setCookie(seller, response);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("设置用户登录cookie失败!");
		}
	    logger.info(seller.toString());
		return seller;
	}
	
	/**
	 * 新用户授权，初始化用户数据，并且开启主动通知服务
	 *  三个月数据：
	 *	a)  首先，通过taobao.topats.trades.sold.get异步获取3个月内到昨天23:59:59创建的订单详情
	 *		建议大卖家分成3次同步，以提升效率
	 *	b)  然后，通过taobao.trades.sold.increment.get获取从今天00:00:00到现在的增量订单ID，再通过taobao.trade.fullinfo.get获取订单详情
	 *		建议启动异步线程，适当切分时段来同步这小部分订单
	 * jack
	 * 2013-12-26
	 */
	private boolean maintainUser(TaoBaoSeller seller){
		TaoBaoSeller oldSeller = getSellerById(seller.getTaobao_user_id());
		if(oldSeller == null){    //新授权用户保存到本地库中
			if(!saveSeller(seller)){
				logger.error("新授权用户，保存到本地库中失败！" + seller);
				return false;
			}
			sellerConfigService.saveSellerConfigDefault(seller);     //新授权用户保存一份默认的自动评价设置
		}else if(oldSeller != null && !oldSeller.getAccess_token().equalsIgnoreCase(seller.getAccess_token())){
			if(!updateSeller(seller)){
				logger.error("用户sessionKey更新到本地库中失败！" + seller);
				return false;
			}
			logger.info("用户sessionKey更新成功");
		}
		return true;
	}
	
	@Override
	public TaoBaoSeller getSellerByNick(String nick){
		if(!StringUtil.isEmpty(nick)){
			return userDao.getSellerByNick(nick);
		}
		return null;
	}

	@Override
	public User getUserByUserName(String userName) throws Exception {
		if(StringUtil.isEmpty(userName)){
			return null;
		}
		return userDao.getUserByName(userName);
	}

	@Override
	public boolean userRegister(User user) throws Exception {
		if(user == null){
			return false;
		}
		userValidate(user);
		return userDao.userRegister(user);
	}
	
	private void userValidate(User user) throws Exception{
		if(StringUtil.isEmpty(user.getUserName())){
			throw new DaoException("注册失败：用户名输入错误！");
		}
		if(StringUtil.isEmpty(user.getEmail())){
			throw new DaoException("注册失败：邮箱输入错误！");
		}
		User existUser = getUserByUserName(user.getUserName());
		if(existUser != null){
			throw new DaoException("注册失败：用户已经存在！");
		}
		
	}

	@Override
	public List<User> getUserList() {
		return userDao.getUserListByCondition(null);
	}

	@Override
	public TaoBaoSeller getSellerById(String sellerId) {
		if(!StringUtil.isEmpty(sellerId)){
			return userDao.getSellerById(sellerId);
		}
		return null;
	}

	@Override
	public boolean saveSeller(TaoBaoSeller seller) {
		if(seller == null){
			return false;
		}
		return userDao.saveSeller(seller);
	}
	
	private boolean updateSeller(TaoBaoSeller seller) {
		if(seller == null){
			return false;
		}
		return userDao.updateSeller(seller);
	}

	@Override
	public TaoBaoSeller getCurrentSeller(HttpServletRequest request) {
		if (!loginService.isSellerLogined(request)) {
			return null;
		}
		String taobao_user_id = CookieUtil.getCookieByDomain(request, RateConstant.SELLER_SESSION_ID_NAME, RateConstant.WORKSMAP_CENTER_DOMAIN);
		return getSellerById(taobao_user_id);
	}
	
}
